package ru.mipt.sport.gui.registry;

import javax.persistence.EntityManager;
import javax.swing.event.TableModelEvent;
import ru.mipt.sport.gui.model.PeopleTableModel;
import ru.mipt.sport.model.interfaces.Person;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author Danon
 */
public class PeopleRegistryWindow extends javax.swing.JFrame {

    private final DBUtils db = DBUtils.getInstance();

    /**
     * Creates new form PeopleRegistryWindow
     */
    public PeopleRegistryWindow() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        peopleTable = new javax.swing.JTable();
        addPersonButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("People Registy");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        peopleTable.setModel(new PeopleTableModel());
        peopleTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        peopleTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                peopleTableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(peopleTable);

        addPersonButton.setText("Add Person...");
        addPersonButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPersonButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(addPersonButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addPersonButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addPersonButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPersonButtonActionPerformed
        AddPersonDialog dlg = new AddPersonDialog(this, true, null);
        dlg.setVisible(true);
        if (dlg.getReturnStatus() == AddPersonDialog.RET_OK) {
            Person p = dlg.getPerson();
            if (p == null) {
                return;
            }
            synchronized (db) {
                try {
                    EntityManager em = db.getEntityManager(true);
                    em.merge(p);
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            PeopleTableModel model = (PeopleTableModel) peopleTable.getModel();
            model.refresh();
            peopleTable.tableChanged(new TableModelEvent(model));
        }

    }//GEN-LAST:event_addPersonButtonActionPerformed

    private void peopleTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peopleTableMouseClicked
        if (evt != null && evt.getClickCount() < 2) {
            return;
        }
        PeopleTableModel model = (PeopleTableModel) peopleTable.getModel();
        if (peopleTable.getSelectedRow() < 0) {
            return;
        }
        Person person = model.getItemAt(peopleTable.getSelectedRow());
        AddPersonDialog dlg = new AddPersonDialog(this, true, person);
        dlg.setVisible(true);
        if (dlg.getReturnStatus() == AddPersonDialog.RET_OK) {
            Person p = dlg.getPerson();
            if (p == null) {
                return;
            }
            synchronized (db) {
                try {
                    EntityManager em = db.getEntityManager(true);
                    em.merge(p);
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            model.refresh();
            peopleTable.repaint();
        }

    }//GEN-LAST:event_peopleTableMouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        db.close();
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PeopleRegistryWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PeopleRegistryWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PeopleRegistryWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PeopleRegistryWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PeopleRegistryWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addPersonButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable peopleTable;
    // End of variables declaration//GEN-END:variables
}
